<?php
	$required = false;
	$title = stripslashes($_POST['title']);
	
	if (function_exists('sanitize_url')) {
		$url = sanitize_url(strip_tags(stripslashes(($_POST['url']))));
	} else {
		$url = clean_url(strip_tags(stripslashes(($_POST['url']))));
	}
	
	switch ($_GET['page']):
		case 'quote':
			$page = 'quote';

			$form = '<dt><label for="title">Title:</label></dt>';
			$form .= '<dd><input type="text" name="title" id="title" value="" /></dd>';
			$form .= '<dt><label for="quote">Quote:</label> (required)</dt>';
			$form .= '<dd><textarea name="quote" id="quote" class="quote"></textarea></dd>';
			$form .= '<dt><label>Source</label></dt>';
			$form .= '<dd><p>This can either be:</p>';
			$form .= '<ul><li>Name and URL</li><li>Name</li><li>URL</li><li>Custom</li></ul>';
			$form .= '<dl>';
			$form .= '<dt><label for="name">Name:</label></dt>';
			$form .= '<dd><input type="text" name="name" id="name" value="" /></dd>';
			$form .= '<dt><label for="url">URL:</label></dt>';
			$form .= '<dd><input type="text" name="url" id="url" value="" /></dd>';
			$form .= '<dt><label for="custom">Custom:</label></dt>';
			$form .= '<dd><script type="text/javascript">edToolbar()</script><textarea name="custom" id="custom"></textarea><script type="text/javascript">var edCanvas = document.getElementById("custom");</script></dd>';
			$form .= '</dl>';
			$form .= '</dd>';

			if (isset($_POST['publish'])) {
				$quote = stripslashes($_POST['quote']);
				$name = stripslashes($_POST['name']);
				$custom = stripslashes($_POST['custom']);
				
				$content = '<blockquote>';
				$content .= "\n" . $quote . "\n";
	
				if (!empty($name) || !empty($url) || !empty($custom)) {				
					switch (true):
						case ($name && $url):
							$source = '<cite><a href="'.$url.'">'.$name.'</a></cite>';
							break;
						case ($name):
							$source = $name; 
							break;
						case ($url):
							$source = '<cite><a href="'.$url.'">'.$url.'</a></cite>';
							break;
						case ($custom):
							$source = $custom;
							break;
					endswitch;
						
					$content .= "\n" . '&mdash; ' . $source . "\n";
				}
				
				$content .= '</blockquote>';
			
				if (!empty($quote))
					$required = true;
			}
			break;
		
		case 'video':
			$page = 'video';
			
			$form = '<dt><label for="title">Video Title:</label></dt>';
			$form .= '<dd><input type="text" name="title" id="title" value="" /></dd>';
			$form .= '<dt><label>Video URL or Embed-tag</label> (required)</dt>';
			$form .= '<dd>';
			$form .= '<p>This can be a URL from video sites like YouTube or Google Video, or the raw Embed-tag from any video/flash site. (ie. http://youtube.com/watch?v=1kdRYdQ5lZo)</p>';
			$form .= '<dl>';
			$form .= '<dt><label for="url">URL:</label></dt>';
			$form .= '<dd><input type="text" name="url" id="url" value="" /></dd>';
			$form .= '<dt><label for="embedtag">Embed-tag:</label></dt>';
			$form .= '<dd><textarea name="embedtag" id="embedtag"></textarea></dd>';
			$form .= '</dl>';
			$form .= '</dd>';
			$form .= '<dt><label for="caption">Caption:</label></dt>';
			$form .= '<dd><script type="text/javascript">edToolbar()</script><textarea name="caption" id="caption"></textarea><script type="text/javascript">var edCanvas = document.getElementById("caption");</script></dd>';

			if (isset($_POST['publish'])) {
				$embedtag = stripslashes($_POST['embedtag']);
				$caption = stripslashes($_POST['caption']);
				
				if (!empty($url)) {
					switch (true):
						case preg_match('#youtube.com/watch#i', $url):
							$url = preg_replace('#youtube.com/watch\?v=#i', 'youtube.com/v/', $url);
							$content = '<object width="425" height="350"><param name="movie" value="'.$url.'"></param><param name="wmode" value="transparent"></param><embed src="'.$url.'" type="application/x-shockwave-flash" wmode="transparent" width="425" height="350"></embed></object>';
							break;
							
						case preg_match('#video.google.com/videoplay#i', $url):
							$url = preg_replace('#video.google.com/videoplay\?docid=#i', 'video.google.com/googleplayer.swf?docId=', $url );					
							$content = '<embed style="width:400px; height:326px" id="VideoPlayback" type="application/x-shockwave-flash" src="'.$url.'" flashvars=""> </embed>';	
							break;
							
						case preg_match('#vimeo.com/#i', $url);
							$url = preg_replace('#vimeo.com/#i', 'vimeo.com/moogaloop.swf?clip_id=', $url);
							$content = '<object type="application/x-shockwave-flash" width="480" height="360" data="'.$url.'&amp;server=vimeo.com&amp;fullscreen=1&amp;show_title=1&amp;show_byline=1&amp;show_portrait=1&amp;color=00ADEF">	<param name="quality" value="best" />	<param name="allowfullscreen" value="true" />	<param name="scale" value="showAll" />	<param name="movie" value="'.$url.'&amp;server=vimeo.com&amp;fullscreen=1&amp;show_title=1&amp;show_byline=1&amp;show_portrait=1&amp;color=00ADEF" /></object>';
							break;
							
						case preg_match('#revver.com/watch/#i', $url);
							$url = preg_replace('#http://one.revver.com/watch/#i', '', $url);
							$content = '<embed type="application/x-shockwave-flash" src="http://flash.revver.com/player/1.0/player.swf" pluginspage="http://www.macromedia.com/go/getflashplayer" scale="noScale" salign="TL" bgcolor="#000000" allowScriptAccess="always" flashvars="mediaId='.$url.'&affiliateId=0&allowFullScreen=true" allowfullscreen="true" height="392" width="480"></embed>';
							break;
							
						case preg_match('#metacafe.com/watch/#i', $url);					
							if (substr($url, -1, 1) == '/')
								$url = substr_replace($url, '', -1, 1);
							
							$url = preg_replace('#watch/(.+)#i', 'fplayer/\1\2.swf', $url);							
							$content = '<embed src="'.$url.'" width="400" height="345" wmode="transparent" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"> </embed>';
							break;
							
						default:
							$content = $url;
							break;
					endswitch;
				} else {
					$content = $embedtag;
				}
							
				if (!empty($caption))
					$content .= "\n\n" . $caption;
				
				if (!empty($url) || !empty($embedtag))
					$required = true;
			}
			break;
		
		case 'link':
			$page = 'link';
			
			$form = '<dt><label for="title">Name:</label></dt>';
			$form .= '<dd><input type="text" name="title" id="title" value="" /></dd>';
			$form .= '<dt><label for="url">Address or URL:</label> (required)</dt>';
			$form .= '<dd><input type="text" name="url" id="url" value="" /></dd>';	
			$form .= '<dt><label for="description">Description:</label></dt>';
			$form .= '<dd><script type="text/javascript">edToolbar()</script><textarea name="description" id="description"></textarea><script type="text/javascript">var edCanvas = document.getElementById("description");</script></dd>';

			if (isset($_POST['publish'])) {		
				$description = stripslashes($_POST['description']);
				
				if (empty($title)) $title = $url;
					
				if (!empty($title) && !empty($url)) {
					$content = '<a href="'.$url.'">'.$title.'</a>';
					
					if (!empty($description))
						$content .= "\n\n" . $description;
				}
				
				if (!empty($url))
					$required = true;	
			}				
			break;
			
		case 'photo':
			$page = 'photo';
							
			$upload_path = ABSPATH . get_option('upload_path');			
			$upload = false;

			if (is_writable($upload_path) && current_user_can('upload_files')) {
				$enctype = ' enctype="multipart/form-data"';			
				$upload_message = ' or upload an image';
				
				$upload_input .= '<dt><label for="upload">Upload:</label></dt>';
				$upload_input .= '<dd><input type="file" name="upload" id="upload" />';
				$upload_input .= '<p>Uploads will be stored in <code>'.attribute_escape(str_replace(ABSPATH, '', $upload_path)).'</code> folder.</p></dd>';			
			}
			
			$form = '<dt><label for="title">Photo Title:</label></dt>';
			$form .= '<dd><input type="text" name="title" id="title" value="" /></dd>';
			$form .= '<dt><label>Photo</label> (required)</dt>';
			$form .= '<dd>';
			$form .= '<p>This can be any image URL'.$upload_message.'.</p>';
			$form .= '<dl>';
			
			$form .= $upload_input;

			$form .= '<dt><label for="url">URL:</label></dt>';
			$form .= '<dd><input type="text" name="url" id="url" value="" />';
			$form .= '<p>Specify image by URL. This can be any valid type of image. (ie. '.get_bloginfo('url').'/photo.jpg)</p></dd>';
			$form .= '</dl>';
			$form .= '</dd>';
			$form .= '<dt><label for="caption">Caption:</label></dt>';
			$form .= '<dd><script type="text/javascript">edToolbar()</script><textarea name="caption" id="caption"></textarea><script type="text/javascript">var edCanvas = document.getElementById("caption");</script></dd>';	

			if (isset($_POST['publish'])) {			
				$image_types = array(
								'image/jpeg',
								'image/gif',
								'image/png'
								);
				
				$upload_filetype = wp_check_filetype($_FILES['upload']['name']);
				$url_filetype = wp_check_filetype(basename($url));
				
				$uploads = wp_upload_dir();
				
				$caption = stripslashes($_POST['caption']);	
			
				if (!empty($_FILES['upload']) || !empty($url)) {
					// Ewwww code ahead.. help!				
					if (is_writable($upload_path)) {
						if (isset($_FILES['upload']['name']) && in_array($upload_filetype['type'], $image_types)) {
							$type = $upload_filetype['type']; 
							$file = $_FILES['upload']['name'];
							unset($url);
							$upload = true;
						} elseif (isset($url) && in_array($url_filetype['type'], $image_types) && current_user_can('upload_files')) {
							$type = $url_filetype['type']; 
							$file = basename($url);
							unset($_FILES['upload']['name']);
							$upload = true;	
						}
					}
				
					if ($upload) {							
						$number = '';			
						$filename = str_replace('#', '_', $file);
						$filename = str_replace(array( '\\', "'"), '', $filename);		
			
						$path_parts = pathinfo($filename);
						$ext = $path_parts['extension'];		
			
						if (empty($ext))
							$ext = '';
						else
							$ext = ".$ext";
							
						while (file_exists($uploads['path'] . "/" . $filename)) {
							if ('' == "$number$ext")
								$filename = $filename . ++$number . $ext;
							else
								$filename = str_replace("$number$ext", ++$number . $ext, $filename);
						}
						
						$filename = str_replace($ext, '', $filename);
						$filename = sanitize_title_with_dashes($filename) . $ext;
						
						$new_file = $uploads['path'] . "/" . $filename;
			
						if (isset($_FILES['upload']['name']) && in_array($upload_filetype['type'], $image_types)) {	
							@ move_uploaded_file($_FILES['upload']['tmp_name'], $new_file);	
						}
						
						if (isset($url) && in_array($url_filetype['type'], $image_types)) {
							$fp = fopen($new_file, 'w');
							fwrite($fp, _file_get_contents($url));
							fclose($fp);	
						}
						
						$stat = stat(dirname($new_file));
						$perms = $stat['mode'] & 0000666;
						@ chmod($new_file, $perms);
						
						$width = '500'; // Default image size
						$image_attr = getimagesize($new_file);
						
						if ($image_attr[0] > $width) {
							$image_ratio = $image_attr[0] / $width;
							$new_width = $width;
							$new_height = $image_attr[1] / $image_ratio;
							
							$resized = imagecreatetruecolor($new_width, $new_height);
							
							if (function_exists('imageantialias'))
								imageantialias($resized, TRUE);
							
							$resized_file = str_replace($ext, '', $new_file); 
							$resized_file = $resized_file . ".resized" . $ext;
							@ copy($new_file, $resized_file);
								
							switch ($type):
								case 'image/jpeg':
									$image = imagecreatefromjpeg($new_file);
									@ imagecopyresized($resized, $image, 0, 0, 0, 0, $new_width, $new_height, $image_attr[0], $image_attr[1]);
									@ imagejpeg($resized, $resized_file, 90);
									break;
								case 'image/gif':
									$image = imagecreatefromgif($new_file);
									@ imagecopyresized($resized, $image, 0, 0, 0, 0, $new_width, $new_height, $image_attr[0], $image_attr[1]);
									@ imagegif($resized, $resized_file);
									break;
								case 'image/png':
									$image = imagecreatefrompng($new_file);
									@ imagecopyresized($resized, $image, 0, 0, 0, 0, $new_width, $new_height, $image_attr[0], $image_attr[1]);
									@ imagepng($resized, $resized_file);
									break;
							endswitch;
			
							imagedestroy($resized);
							
							$resized_url = $uploads['url'] . "/" . basename($resized_file); 
						}

						/*$image_attr = getimagesize($new_file); 
			
						if ($image_attr[0] <= $width)	{
							$filename = basename($new_file);
						} else {
							wp_create_thumbnail($new_file, $width);
							$filename = preg_replace('!(\.[^.]+)?$!', '.thumbnail' . '$1', basename($new_file), 1);
						}*/				
			
						$thumbnail = wp_create_thumbnail($new_file, 128);						
						
						$url = $uploads['url'] . "/" . $filename;
						
						if (!empty($resized_url))
							$content .= '<a href="'.$url.'"><img src="'.$resized_url.'" alt="'.$title.'" /></a>';					
						else
							$content .= '<img src="'.$url.'" alt="'.$title.'" />';							
						
						$required = true;
					
					} elseif (!$upload && isset($url) && in_array($url_filetype['type'], $image_types)) {
					
						$content .= '<img src="'.$url.'" alt="'.$title.'" />';
						$required = true;
					
					}
				}
				
				if (!empty($caption))
					$content .= "\n\n" . $caption;
			}
			break;
		
		case 'chat':
			$page = 'chat';

			$form = '<dt><label for="title">Title:</label></dt>';
			$form .= '<dd><input type="text" name="title" id="title" value="" /></dd>';
			$form .= '<dt><label for="dialogue">Dialogue:</label> (required)</dt>';
			$form .= '<dd><p>Example<br />';			
			$form .= 'Guy: So she got hit by a rickshaw.<br />Girl: How on earth do you get hit by a rickshaw?<br />Guy: I don\'t know, she just did.<br />';
			$form .= '</p></dd>';
			$form .= '<dd><script type="text/javascript">edToolbar()</script><textarea name="dialogue" id="dialogue"></textarea><script type="text/javascript">var edCanvas = document.getElementById("dialogue");</script></dd>';				
			
			if (isset($_POST['publish'])) {
				$dialogue = stripslashes($_POST['dialogue']);
			
				$content = $dialogue;
				
				if (!empty($dialogue))
					$required = true;
			}
			break;
			
		case 'text':
			wp_redirect('post-new.php');
			exit();
			break;
	endswitch; 

	if (current_user_can('publish_posts')) {
		global $post, $user_ID;
		
		$pending = get_others_pending($user_ID);
		$count = count($pending);
		$limit = 3;
	
		if ($pending) {
			echo '<div class="wrap"><p><strong>Pending Review:</strong> ';
			$i = 0;
			foreach ($pending as $post) {
				$i++;
				if ( $i > $limit )
					break;
				echo '<a href="post.php?action=edit&amp;post=' . $post->ID . '">';
				( '' == the_title('', '', FALSE) ) ? printf( __('Post #%s'), $post->ID ) : the_title();
				echo '</a>';
				if ($i < min($count, $limit))
					echo ', ';
			}
			
			if ($i > $limit)
				printf(__(' and <a href="%s">%d more</a>'), 'edit.php?post_status=pending', $count - $limit);
			
			echo '.</p></div>';
		}
	}

	global $wpdb, $options;
	
	if (isset($_POST['publish']) && $required) {
		$parent_file = 'post-new.php';
		$submenu_file = 'post-new.php';
		check_admin_referer('add-post');
		
		$post_status = current_user_can('publish_posts') ? 'publish' : 'pending';
		
		$data = array(
			'post_title' => $wpdb->escape($title),
			'post_content' => $wpdb->escape($content),
			'post_date' => $date,
			'post_category' => $_POST['post_category'],
			'post_status' => $post_status,
			'tags_input' => $_POST['tags']
		);
		
		$post_ID = wp_insert_post($data);
		
		if ($upload) {
			$attachment = array(
				'post_title' => $wpdb->escape($title),
				'post_content' => $wpdb->escape($caption),
				'post_type' => 'attachment',
				'post_parent' => $post_ID,
				'post_mime_type' => $type,
				'guid' => $url
			);
			
			$id = wp_insert_attachment($attachment, $new_file, $post_ID);
			wp_update_attachment_metadata($id, wp_generate_attachment_metadata($id, $new_file));
		}
		
		echo '<div id="message" class="updated fade"><p><strong>'._capitalize($page).' saved.</strong> <a href="'.get_permalink($post_ID).'">View post &raquo;</a></p></div>';
	}
?>

<div class="wrap">

	<h2 id="write-post">Add a <?php echo _capitalize($page) ?></h2>
	
	<form action="" method="post" id="post"<?php echo $enctype ?>>
	
		<input type="hidden" name="post_category[]" value="<?php echo $options[$page] ?>" />	
		<?php wp_nonce_field('add-post') ?>
		
		<fieldset id="postdiv">	
		<dl>
		<?php echo $form ?>
		<dt><label for="tags">Tags:</label> (separate multiple tags with commas: cats, pet food, dogs)</dt>
		<dd><input type="text" name="tags" id="tags" value="" /></dd>
		</dl>		
		</fieldset>
		
		<div class="submit">
			<input type="submit" name="publish" value="<?php if (current_user_can('publish_posts')) echo 'Publish'; else echo 'Submit for Review'; ?>" />
		</div>
							
	</form>

</div>